<template>
	<view class="forgot-page">
		<uv-navbar title="注册" placeholder bg-color="transparent" auto-back left-icon-color="#757575"
			title-style="color: #000000; font-size: 32rpx" />
		<view class="forgot-body">
			<uv-form label-position="top" :model="forms" :rules="rules" ref="formRef">
				<uv-form-item required label="机构名称" prop="serviceOrgName" label-width="400rpx" @click="showInstitution">
					<uv-input v-model="forms.serviceOrgName" placeholder="请选择" disabled disabled-color="#ffffff"
						suffix-icon="arrow-right" suffix-icon-style="color: #BDBDBD" />
				</uv-form-item>
				<uv-form-item required label="用户姓名" prop="nickName" label-width="400rpx">
					<uv-input v-model="forms.nickName" disabled-color="#ffffff" clearable placeholder="请输入用户姓名"
						maxlength="20" />
				</uv-form-item>
				<uv-form-item required label="手机号码" prop="phonenumber" label-width="400rpx">
					<uv-input v-model="forms.phonenumber" disabled-color="#ffffff" clearable placeholder="请输入手机号码"
						maxlength="11" @change="changePhone" />
				</uv-form-item>
				<uv-form-item required label="密码" prop="password" label-width="400rpx">
					<uv-input v-model="forms.password" disabled-color="#ffffff" clearable
						:type="showPassword ? 'text' : 'password'" placeholder="请输入密码" maxlength="20"
						suffix-icon="eye-fill" :suffix-icon-style="{
              color: showPassword ? '#212121' : '#BDBDBD',
            }" @suffix="() => (showPassword = !showPassword)" />
				</uv-form-item>
				<uv-form-item required label="性别" prop="sexName" label-width="400rpx" @click="showSex">
					<uv-input v-model="forms.sexName" placeholder="请选择" disabled disabled-color="#ffffff"
						suffix-icon="arrow-right" suffix-icon-style="color: #BDBDBD" />
				</uv-form-item>
				<uv-form-item required label="身份证号码" prop="idCard" label-width="400rpx">
					<uv-input v-model="forms.idCard" disabled-color="#ffffff" clearable placeholder="请输入身份证号码"
						maxlength="18" />
				</uv-form-item>
				<uv-form-item required label="身份证照片上传" prop="idCardPhoto" label-width="400rpx">
					<g-upload v-model:value="forms.idCardPhoto" multiple :max="2" text="正反面上传" />
				</uv-form-item>
				<uv-form-item required label="资格证书" prop="qualificationName"
					label-width="400rpx">
					<uv-input v-model="forms.qualificationName" disabled-color="#ffffff" clearable
						placeholder="请输入资格证书名称" maxlength="30" />
				</uv-form-item>
				<uv-form-item required label="资格证号" prop="qualificationCode"
					label-width="400rpx">
					<uv-input v-model="forms.qualificationCode" disabled-color="#ffffff" clearable
						placeholder="请输入资格证书号" maxlength="30" />
				</uv-form-item>
				<uv-form-item required v-if="forms.userType == '03'" label="资格证件有效期" prop="certificateValidityPeriodName"
					label-width="400rpx" @click="showAging">
					<uv-input v-model="forms.certificateValidityPeriodName" placeholder="请选择" disabled
						disabled-color="#ffffff" suffix-icon="arrow-right" suffix-icon-style="color: #BDBDBD" />
				</uv-form-item>
				<uv-form-item required v-if="forms.userType == '03'" label="证件有效期选择" prop="qualificationStartDate"
					label-width="400rpx" @click="showDate">
					<view class="date-box">
						<view v-if="!forms.qualificationStartDate || !forms.qualificationEndDate" class="placeholder"
							>选择有效期</view
						>
						<view v-else class="date">
							{{ forms.qualificationStartDate }} - {{ forms.qualificationEndDate }}
						</view>
						<uv-icon name="arrow-right" color="#BDBDBD" size="36rpx" />
					</view>
				</uv-form-item>
				<uv-form-item required label="资格证件照上传" prop="qualification"
					label-width="400rpx">
					<g-upload v-model:value="forms.qualification" multiple :max="5" />
				</uv-form-item>
				<uv-form-item required label="人脸采集" prop="faceUrl" label-width="400rpx">
					<g-upload v-model:value="forms.faceUrl" icon="camera-fill" text="点击拍照" multiple :max="5" />
				</uv-form-item>
			</uv-form>
			<view class="btn-box">
				<uv-button
					text="提交"
					type="primary"
					shape="circle"
					color="#4EA770"
					:custom-style="{width: '100%'}"
					@click="handleSubmit"
				/>
			</view>
		</view>
		<uv-popup ref="institutionRef" mode="bottom" @maskClick="closeInstitution">
			<view>
				<uv-toolbar confirm-color="#4EA770" title="选择机构" @cancel="closeInstitution" @confirm="confirmInstitution" />
				<uv-search placeholder="请输入搜索机构名称" v-model="institution" :show-action="false" :maxlength="50" margin="auto 30rpx 30rpx" />
				<scroll-view scroll-y style="height: 40vh;">
					<uv-radio-group
						v-model="serviceOrgId" 
						placement="column" 
						icon-placement="right"
						border-bottom
						active-color="#4EA770"
						>
							<uv-radio
								v-for="i in filterInstitutionList"
								:key="i.userId"
								:name="i.userId"
								:label="i.nickName"
								:label-color="serviceOrgId == i.userId ? '#4EA770' : '#303133'"
								:custom-style="{
									padding: '20rpx',
								}"
							/>
					</uv-radio-group>
				</scroll-view>
			</view>
		</uv-popup>
		<uv-picker ref="sexRef" :columns="sexList" key-name="label" @confirm="confirmSex" />
		<uv-picker ref="agingRef" :columns="agingList" key-name="label" @confirm="confirmAging" />
    <uv-calendars
      ref="dateRef"
      mode="range"
      :round="0"
      color="#4EA770"
      confirm-color="#4EA770"
      allow-same-day
      :date="
			forms.qualificationStartDate && forms.qualificationEndDate
          ? [forms.qualificationStartDate, forms.qualificationEndDate]
          : ''
      "
      @confirm="confirmDate"
    />
	</view>
</template>
<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed
	} from "vue";
	import {
		postRegister,
		getUserType
	} from "@/request/login.js";

	const formRef = ref(); // 表单ref
	const forms = reactive({
		serviceOrgId: -1, // 机构名称id
		serviceOrgName: "总平台", // 机构名称
		username: "", // 账户名
		nickName: "", // 用户姓名
		phonenumber: "", // 手机号码
		password: "", // 密码
		sex: "", // 性别
		sexName: "", // 性别名称
		idCard: "", // 身份证号码
		idCardPhoto: [], // 身份证照片
		qualificationName: "", // 资格证书
		qualificationCode: "", // 资格证号
		certificateValidityPeriod: "", // 资格证书有效期
		certificateValidityPeriodName: "", // 资格证书有效期名称
		qualificationStartDate: "", // 资格证号开始日期
		qualificationEndDate: "", // 资格证号结束日期
		qualification: [], // 资格证书
		faceUrl: [], // 人脸照片
		userType: "05", // 用户类型
	});
	const rules = reactive({
		// 表单规则
		serviceOrgName: [{
			required: true,
			message: "请选择机构名称",
			trigger: ["blur", "change"]
		}, ],
		nickName: [{
			required: true,
			message: "请输入姓名",
			trigger: "blur"
		}],
		phonenumber: [{
				required: true,
				message: "请输入手机号码",
				trigger: "blur"
			},
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback(new Error("请输入手机号码"));
					} else if (!/^1[3456789]\d{9}$/.test(value)) {
						callback(new Error("请输入正确的手机号码"));
					} else {
						callback();
					}
				},
			},
		],
		password: [{
				required: true,
				message: "请输入密码",
				trigger: "blur"
			},
			{
				min: 6,
				max: 16,
				message: "密码长度在6-16位之间",
				trigger: "blur",
			},
		],
		sexName: [{
			required: true,
			message: "请选择性别",
			trigger: ["blur", "change"]
		}],
		idCard: [{
				required: true,
				message: "请输入身份证号码",
				trigger: "blur"
			},
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback(new Error("请输入身份证号码"));
					} else if (!/^\d{17}[\dX]$/.test(value)) {
						callback(new Error("请输入正确的身份证号码"));
					} else {
						callback();
					}
				},
			},
		],
		idCardPhoto: [{
				required: true,
				type: "array",
				message: "请上传身份证照片",
				trigger: ["blur", "change"],
			},
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback(new Error("请上传身份证照片"));
					} else if (value.length != 2) {
						callback(new Error("请上传2张身份证照片"));
					} else {
						callback();
					}
				},
			},
		],
		qualificationName: [{
			required: true,
			message: "请输入机构证件",
			trigger: "blur"
		}],
		qualificationCode: [{
			required: true,
			message: "请输入机构证件号",
			trigger: "blur"
		}],
		certificateValidityPeriodName: [{
			required: true,
			message: "请选择机构证件有限期",
			trigger: ["blur", "change"],
		}, ],
		qualificationStartDate: [{
			required: true,
			message: "请选择机构证件有限期日期",
			trigger: ["blur", "change"],
		}, ],
		qualification: [{
			required: true,
			type: "array",
			message: "请上传机构证书照片",
			trigger: "change"
		}, ],
		faceUrl: [{
			required: true,
			type: "array",
			message: "请上传人脸照片",
			trigger: "change"
		}, ],
	});
	const institutionRef = ref(); // 机构列表ref
	const institution = ref(''); // 过滤机构名称
	const serviceOrgId = ref(-1); // 临时机构id
	const institutionList = ref([]); // 机构列表
	const showPassword = ref(false); // 密码是否显示
	const sexRef = ref(); // 性别列表ref
	const sexList = ref([
		[
			{ label: "男", value: 0 },
			{ label: "女", value: 1 },
			{ label: "未知", value: 2 },
		],
	]); // 性别列表
	const agingRef = ref(); // 有效期列表ref
	const agingList = ref([
		[
			{ label: "长期", value: 1 },
			{ label: "临期", value: 2 },
		],
	]); // 有效期列表
	const dateRef = ref(); // 日期有效期ref

	// 获取过滤后的机构列表
	const filterInstitutionList = computed(() => {
		return institutionList.value?.filter((i) => {
			return i.nickName.includes(institution.value);
		});
	})

	onMounted(() => {
		getUserTypeList();
	});

	// 提交
	const handleSubmit = () => {
		formRef.value
			.validate()
			.then((valid) => {
				if (valid) {
					let data = Object.assign({}, forms);
					delete data.serviceOrgName;
					delete data.sexName;
					delete data.certificateValidityPeriodName;
					data.idCardPhoto = data.idCardPhoto?.join(",");
					data.qualification = data.qualification?.join(",");
					data.faceUrl = data.faceUrl?.join(",");
					postRegister(data).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: "提交成功",
								icon: "none",
								success: () => {
									setTimeout(() => {
										uni.navigateBack({
											delta: 1,
										});
									}, 2000);
								},
							});
						}
					});
				}
			})
			.catch(() => {});
	};

	// 获取机构列表
	const getUserTypeList = () => {
		getUserType({
			userType: "01"
		}).then((res) => {
			institutionList.value = res.data;
			institutionList.value.unshift({
				userId: -1,
				nickName: "总平台"
			});
		});
	};

	// 同步账户名
	const changePhone = (val) => {
		forms.username = val;
	};

	// 机构弹窗
	const showInstitution = () => {
		institutionRef.value.open();
		serviceOrgId.value = forms.serviceOrgId;
	};

	// 关闭机构
	const closeInstitution = () => {
		institutionRef.value.close();
		serviceOrgId.value = null;
	};

	// 确认机构
	const confirmInstitution = () => {
		forms.serviceOrgId = serviceOrgId.value;
		forms.serviceOrgName = institutionList.value.find((i) => i.userId == serviceOrgId.value)?.nickName;
		closeInstitution();
	};

	// 性别弹窗
	const showSex = () => {
		sexRef.value.open();
	};

	// 确认性别
	const confirmSex = (item) => {
		forms.sex = item.value[0]?.value;
		forms.sexName = item.value[0]?.label;
	};

	// 日期弹窗
	const showDate = () => {
		dateRef.value.open();
	};

	// 确认日期
	const confirmDate = (item) => {
		forms.qualificationStartDate = item.range.before;
		forms.qualificationEndDate = item.range.after;
	};

	// 有效期弹窗
	const showAging = () => {
		agingRef.value.open();
	};

	// 确认有效期
	const confirmAging = (item) => {
		forms.certificateValidityPeriod = item.value[0]?.value;
		forms.certificateValidityPeriodName = item.value[0]?.label;
	};
</script>
<style lang="scss" scoped>
	.forgot-page {
		width: 100%;
		height: 100vh;
		background-image: linear-gradient(180deg, #fff 0%, #4ea770 100%);
		.forgot-body {
			max-height: calc(100vh - 160rpx);
			background: #fff;
			box-shadow: 0 0 20rpx 2rpx rgba(78, 167, 112, 0.2);
			border-radius: 20rpx;
			margin: 8rpx 40rpx;
			padding: 20rpx 20rpx 0;
			overflow-y: auto;
			.btn-box {
				position: sticky;
				bottom: 0;
				left: 0;
				right: 0;
				padding: 20rpx;
				background-color: #fff;
				border-top: 1px solid #f5f5f5;
				margin-top: 20rpx;
				z-index: 9;
			}
		}
	}
	.date-box {
    height: 70rpx;
		width: 100%;
    padding: 12rpx 16rpx 12rpx;
    box-sizing: border-box;
    background: #ffffff;
    border-radius: 8rpx;
    border: 2rpx solid #dedede;
    display: flex;
		justify-content: space-between;
    align-items: center;
    .placeholder {
      font-size: 28rpx;
      color: #bdbdbd;
      margin-left: 10rpx;
    }
    .date {
      font-size: 28rpx;
      color: #bdbdbd;
      margin-left: 10rpx;
    }
  }
	:deep(.uv-form-item__body__left__content) {
		margin-left: 18rpx;
	}
</style>